import React from "react";
import { useRequest } from "ahooks";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import Select, { SingleValue } from "react-select";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Heading } from "@/components/ui/heading";
import { Input } from "@/components/ui/input";
import { PasswordInput } from "@/components/custom/password-input";
import { Separator } from "@/components/ui/separator";
import { Checkbox } from "@/components/ui/checkbox";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { zodResolver } from "@hookform/resolvers/zod";
import { createColumnHelper } from "@tanstack/react-table";
import { Edit, MoreHorizontal, Trash, Lock } from "lucide-react";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { AlertModal } from "@/components/modal/alert-modal";
import { ResourceI, UserI, RoleI, RoleUserI, EmployeeI } from "@/types";
import PageContainer from "@/components/layout/page-container";
import CustomDndTable from "@/components/ui/custom-dnd-table";
import { useToast } from "@/hooks/use-toast";
import { Plus } from "lucide-react";
import request, { CustomResponse } from "@/api/http_class";
import {
  createUser,
  updateUser,
  searchUserList,
  deleteUser,
  searchRoleList,
  searchResourceList,
  getUserDetail,
  getVbpDepartmentList,
  searchEmployeeList,
  resetUserPassword,
} from "@/api";
import { useSearchParams } from "react-router-dom";
import { encryptStr, isValidJson, passwordStrengthTest } from "@/lib/utils";
// import CustomTable from "@/components/ui/custom-table";

const page: React.FC = () => {
  // 用于监听URL变化，根据table产生的参数更新table的数据
  const [searchParams, setSearchParams] = useSearchParams();
  const { toast } = useToast();

  const [title, setTitle] = React.useState<string>("");
  const [isDeleteSubmitting, setIsDeleteSubmitting] =
    React.useState<boolean>(false);
  // 删除Dialog开关
  const [isAlertOpen, setIsAlertOpen] = React.useState<boolean>(false);
  // 用户表单Dialog开关
  const [isDialogOpen, setIsDialogOpen] = React.useState<boolean>(false);
  // 重置表单Dialog开关
  const [isResetDialogOpen, setIsResetDialogOpen] =
    React.useState<boolean>(false);
  // 用户数量
  const [totalCount, setTotalCount] = React.useState<number>(0);
  const [userList, setUserList] = React.useState<UserI[]>([]);
  const [roleList, setRoleList] = React.useState<RoleI[]>([]);
  const [employeeList, setEmployeeList] = React.useState<EmployeeI[]>([]);
  const [departmentList, setDepartmentList] = React.useState<any>([]);

  const { loading: loadingEmployees, run: runSearchEmployees } = useRequest(
    (paramsString: string) => searchEmployeeList(paramsString),
    {
      manual: false,
      defaultParams: [""],
      onSuccess(resp: any, params: any) {
        console.log(resp.data);
        setEmployeeList(resp.data.data);
      },
      onError(e: any, params: any) {
        toast({
          variant: "destructive",
          title: "获取员工列表失败",
        });
      },
    }
  );

  useRequest((paramsString: string) => searchRoleList(paramsString), {
    manual: false,
    defaultParams: [""],
    onSuccess(resp, params: any) {
      // console.log(params);
      setRoleList(resp.data.data);
    },
    onError(err: any, params: any) {
      console.error("获取数据失败");
      toast({
        variant: "destructive",
        title: "数据获取失败",
        description: `${err.detail}`,
      });
    },
  });

  const { loading, run } = useRequest(
    (paramsString: string) => searchUserList(paramsString),
    {
      manual: true,
      defaultParams: [searchParams.toString()],
      onSuccess(resp, params: any) {
        setUserList(resp.data.data);
        setTotalCount(resp.data.totalCount);
      },
      onError(err: any, params: any) {
        console.error("获取数据失败");
        toast({
          variant: "destructive",
          title: "数据获取失败",
          description: `${err.detail}`,
        });
      },
    }
  );

  useRequest((paramsString: string) => getVbpDepartmentList(paramsString), {
    manual: false,
    defaultParams: [""],
    onSuccess(resp: any, params: any) {
      setDepartmentList(
        resp.data.data.map((item: any) => {
          return {
            value: item.name,
            label: item.name,
          };
        })
      );
    },
    onError(e: any, params: any) {
      console.log(e);
    },
  });

  const formSchema = z
    .object({
      id: z.string().optional(),
      // username: z.string().trim().min(3, { message: "用户名至少3个字符" }),
      username: z.any(),
      // password: z.string().trim().min(6, { message: "用户名至少6个字符" }),
      password: z.string().refine(passwordStrengthTest, {
        message: "密码至少8位，并且应包含大小写、数字和特殊字符",
      }),
      passwordAgain: z.string().optional(),
      isActive: z.boolean().optional(),
      depts: z.any().array(),
      roleIds: z.any().optional(),
      department: z.string().optional(),
      // cellphone: z.string().optional(),
      // email: z.string().optional(),
      // nickname: z.string().optional(),
      fullName: z.string().optional(),
      empCode: z.string().optional(),
      // birthday: z.date().optional(),
      // sex: z.number().optional(),
      // score: z.number().optional(),
      // avatarURL: z.string().optional(),
      // lastLoginAt: z.date().optional(),
      // isSuperuser: z.boolean().optional(),
      // roleUsers: z.any().optional(),
      // roles: z.any().optional(),
      // currentRole: z.any().optional(),
      // resources: z.any().optional(),
      // policies: z.any().optional(),
    })
    .refine((data) => data.password === data.passwordAgain, {
      message: "两次密码必须一致",
      path: ["passwordAgain"],
    });

  const defaultValues = {
    id: undefined,
    username: "",
    password: "",
    passwordAgain: "",
    cellphone: "",
    email: "",
    nickname: "",
    fullName: "",
    department: "",
    birthday: new Date(),
    sex: 0,
    score: 0,
    avatarURL: "",
    lastLoginAt: new Date(),
    isActive: true,
    isSuperuser: false,
    roleUsers: [],
    roles: [],
    currentRole: undefined,
    resources: [],
    // policies: [],
  };

  type FormValuesT = z.infer<typeof formSchema>;

  // 表单部分
  const form = useForm<FormValuesT>({
    resolver: zodResolver(formSchema),
    defaultValues: defaultValues,
    mode: "onChange",
  });

  // 表格中批量导入数量使用
  const handleUploadSubmit = (values: any): Promise<any> => {
    // console.log(values);
    return new Promise((resolve, reject) => {
      if (values.files.length) {
        const formData = new FormData();
        // 将全部数据转换为FormData格式
        values.files.forEach((item: File) => {
          console.log(item);
          formData.append("files", item);
        });
        console.log(formData);
        request({
          // url: `/employees/import/`,
          url: `/users/import/`,
          method: "POST",
          data: formData,
          headers: { "Content-Type": "multipart/form-data" },
        }).then(
          (res: any) => {
            console.log(res);
            resolve(res);
            toast({
              variant: "success",
              title: "数据导入成功",
            });
          },
          (err: any) => {
            console.log(err);
            reject(err);
            toast({
              variant: "destructive",
              title: "数据导入失败",
              description: `${err.detail}`,
            });
          }
        );
      } else {
        reject("no files");
      }
    });
  };

  // 当出现password输入项时，浏览器会自动找username类input并自动填值
  const onUpdateClick = (data: UserI) => {
    console.log(data);
    if (!data || !data.id) {
      toast({
        variant: "destructive",
        title: "无效用户id",
        description: "error",
      });
      return;
    }
    // 取包含此用户的员工列表项
    const params = new URLSearchParams();
    params.set("search", data.username);
    // console.log(params.toString());
    searchEmployeeList(params.toString())
      .then(
        (res: CustomResponse<{ totalCount: number; data: EmployeeI[] }>) => {
          const employee = res.data.data.length ? res.data.data[0] : null;
          // console.log(employee);
          setEmployeeList(res.data.data);
          data &&
            data.id &&
            getUserDetail(data.id).then(
              (res) => {
                console.log(res);
                const processedData = Object.assign(
                  {},
                  defaultValues,
                  Object.fromEntries(
                    Object.entries(res.data).reduce((acc, [key, value]) => {
                      if (value !== null) {
                        // 如果 key 是 'startDate' 并且 value 是一个有效的日期字符串，转换为 Date
                        if (key === "depts") {
                          acc.push([key, JSON.parse(value)]);
                        } else if (key === "roleUsers") {
                          acc.push([
                            "roleIds",
                            value.map((item: RoleUserI) => {
                              return {
                                value: item.role!.id,
                                label: item.role!.name,
                              };
                            }),
                          ]);
                        } else if (key === "username") {
                          acc.push(["username", employee]);
                        } else {
                          acc.push([key, value]);
                        }
                      }
                      return acc;
                    }, [] as [string, any][])
                  )
                );

                // 避免将受控组件的值设置成null，否则会有警告，影响未知
                form.reset(processedData);
                setIsDialogOpen(true);
              },
              (err) => {
                toast({
                  variant: "destructive",
                  title: "数据查询失败",
                  description: `${err.detail}`,
                });
              }
            );
        },
        (err) => {
          toast({
            variant: "destructive",
            title: "数据提交失败",
            description: `${err.detail}`,
          });
        }
      )
      .catch((err) => {
        toast({
          variant: "destructive",
          title: "无效用户id",
          description: `${err.detail}`,
        });
      });
  };

  const resetPasswordFormSchema = z
    .object({
      id: z.string(),
      password: z.string().refine(passwordStrengthTest, {
        message: "密码至少8位，并且应包含大小写、数字和特殊字符",
      }),
      passwordAgain: z.string().optional(),
    })
    .refine((data) => data.password === data.passwordAgain, {
      message: "两次密码必须一致",
      path: ["passwordAgain"],
    });

  type ResetPasswordFormValuesT = z.infer<typeof resetPasswordFormSchema>;

  // 表单部分
  const resetPasswordForm = useForm<ResetPasswordFormValuesT>({
    resolver: zodResolver(resetPasswordFormSchema),
    defaultValues: {},
    mode: "onChange",
  });

  const onDeleteConfirm = (data: UserI) => {
    try {
      setIsDeleteSubmitting(true);
      if (data.id) {
        deleteUser(data.id).then(
          (res: any) => {
            setIsAlertOpen(false);
            setIsDeleteSubmitting(false);
            toast({
              variant: "success",
              title: "删除成功",
              description: "",
            });
            run(searchParams.toString());
          },
          (err) => {
            setIsDeleteSubmitting(false);
            toast({
              variant: "destructive",
              title: "数据提交失败",
              description: `${err.detail}`,
            });
          }
        );
      }
    } catch (error: any) {
      console.log(error);
      toast({
        variant: "destructive",
        title: "删除失败",
      });
    }
  };

  const handleSelectInputChange = (input: string) => {
    console.log(input);
    const selectParams = new URLSearchParams();
    selectParams.set("search", input);
    runSearchEmployees(selectParams.toString());
  };

  // 用户表单form提交操作
  const onFormSubmit = (data: FormValuesT) => {
    // console.log(data);
    let formData = JSON.parse(JSON.stringify(data));
    // console.log(formData);
    if (data.username) {
      formData.username = data.username.code;
    }
    if (data.depts) {
      formData.depts = JSON.stringify(data.depts);
    }
    if (data.roleIds) {
      formData.roleIds = data.roleIds.map((item: any) => {
        console.log(item);
        return item.value;
      });
    }

    if (data.password) {
      formData.password = encryptStr(data.password);
      formData.passwordAgain = encryptStr(data.passwordAgain || "");
    }

    console.log(formData);
    setIsDeleteSubmitting(true);
    if (data.id) {
      updateUser(formData)
        .then(
          (res) => {
            console.log(res);
            toast({
              variant: "success",
              title: "提交成功",
              description: "",
            });
            form.reset();
            setIsDialogOpen(false);
            run(searchParams.toString());
          },
          (err) => {
            toast({
              variant: "destructive",
              title: "数据提交失败",
              description: `${err.detail}`,
            });
          }
        )
        .catch((err) => {
          toast({
            variant: "destructive",
            title: "提交失败",
            description: `${err.detail}`,
          });
        });
    } else {
      createUser(formData)
        .then(
          (res) => {
            console.log(res);
            form.reset();
            setIsDialogOpen(false);
            toast({
              variant: "success",
              title: "提交成功",
              description: "",
            });
            run(searchParams.toString());
          },
          (err) => {
            toast({
              variant: "destructive",
              title: "数据提交失败",
              description: `${err.detail}`,
            });
          }
        )
        .catch((err) => {
          toast({
            variant: "destructive",
            title: "提交失败",
            description: `${err.detail}`,
          });
        });
    }
  };

  const onResetPasswordFormSubmit = (data: ResetPasswordFormValuesT) => {
    const submitData = JSON.parse(JSON.stringify(data));
    submitData.password = encryptStr(data.password);
    submitData.passwordAgain = encryptStr(data.passwordAgain || "");
    resetUserPassword(submitData).then(
      (res) => {
        console.log(res);
        setIsResetDialogOpen(false);
        toast({
          variant: "success",
          title: "提交成功",
        });
      },
      (err) => {
        console.error(err);
        toast({
          variant: "destructive",
          title: "提交失败",
          description: `${err.detail}`,
        });
      }
    );
  };

  const columnHelper = createColumnHelper<UserI>();

  const columns = [
    columnHelper.display({
      id: "select",
      header: (props) => {
        // console.log(props);
        if (props && props.table) {
          return (
            <Checkbox
              checked={props.table.getIsAllPageRowsSelected()}
              onCheckedChange={(value) =>
                props.table.toggleAllPageRowsSelected(!!value)
              }
              aria-label="Select all"
            />
          );
        } else {
          return <Checkbox aria-label="Select all" />;
        }
      },
      footer: (props) => props.column.id,
      cell: (props) => {
        if (props && props.row) {
          return (
            <Checkbox
              checked={props.row.getIsSelected()}
              onCheckedChange={(value) => props.row.toggleSelected(!!value)}
              aria-label="Select row"
            />
          );
        } else {
          return <Checkbox aria-label="Select row" />;
        }
      },
      enableSorting: false,
      enableHiding: true,
    }),
    columnHelper.accessor("id", {
      id: "id",
      header: "ID",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return <span>{row.getValue("id")}</span>;
        }
      },
      enableSorting: true,
      enableHiding: false,
      size: 200,
      maxSize: 200,
    }),
    columnHelper.accessor("username", {
      id: "username",
      header: "用户名",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return <span>{row.getValue("username")}</span>;
        }
      },
      enableSorting: true,
      enableHiding: false,
    }),
    columnHelper.accessor("fullName", {
      id: "fullName",
      header: "姓名",
      enableSorting: true,
      enableHiding: false,
    }),
    columnHelper.accessor("empCode", {
      id: "empCode",
      header: "工号",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return <span>{row.getValue("empCode")}</span>;
        }
      },
      enableSorting: true,
      enableHiding: false,
    }),
    columnHelper.accessor("isActive", {
      id: "isActive",
      header: "在用标记",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return row.getValue("isActive") ? (
            <span>在用</span>
          ) : (
            <span>停用</span>
          );
        }
      },
      enableSorting: true,
      enableHiding: false,
    }),
    columnHelper.accessor("roleUsers", {
      id: "roleUsers",
      header: "角色",
      cell: ({ row }) => {
        return (
          <span>
            {row.getValue("roleUsers")
              ? (row.getValue("roleUsers") as any)
                  .map((item: RoleUserI) => item.role!.name)
                  .join("，")
              : ""}
          </span>
        );
      },
      enableSorting: false,
      enableHiding: false,
    }),
    columnHelper.accessor("depts", {
      id: "depts",
      header: "授权科室",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          let value = [];
          if (isValidJson(row.getValue("depts"))) {
            value = JSON.parse(row.getValue("depts"));
          }
          return <span>{value.map((item: any) => item.value).join(",")}</span>;
        }
      },
      enableSorting: false,
      enableHiding: false,
    }),
    columnHelper.display({
      header: "操作",
      id: "actions",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <>
              <AlertModal
                isOpen={isAlertOpen}
                onClose={() => setIsAlertOpen(false)}
                onConfirm={() => onDeleteConfirm(row.original)}
                loading={isDeleteSubmitting}
              />
              <DropdownMenu modal={false}>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" className="h-8 w-8 p-0">
                    <span className="sr-only">选项</span>
                    <MoreHorizontal className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuLabel></DropdownMenuLabel>
                  <DropdownMenuItem onClick={() => onUpdateClick(row.original)}>
                    <Edit className="mr-2 h-4 w-4" /> 更新
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    onClick={() => {
                      resetPasswordForm.setValue("id", row.original.id!);
                      setIsResetDialogOpen(true);
                    }}
                  >
                    <Lock className="mr-2 h-4 w-4" /> 重置密码
                  </DropdownMenuItem>
                  <DropdownMenuItem onClick={() => setIsAlertOpen(true)}>
                    <Trash className="mr-2 h-4 w-4" /> 删除
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </>
          );
        }
      },
    }),
  ];

  const deptColumnHelper = createColumnHelper<any>();
  const deptColumns = [
    deptColumnHelper.accessor("name", {
      id: "name",
      header: "科室名称",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return <span>{row.getValue("name")}</span>;
        }
      },
      enableSorting: true,
      enableHiding: false,
      size: 200,
      maxSize: 200,
    }),
  ];

  React.useEffect(() => {
    // console.log(searchParams.toString());
    run(searchParams.toString());
  }, [searchParams]);

  return (
    <PageContainer>
      <div className="space-y-4">
        {/* <Breadcrumbs items={breadcrumbItems} /> */}

        <div className="flex items-start justify-between">
          <Heading title={`用户列表`} description="每个用户对应不同的权限" />

          <Button
            variant="outline"
            className="p-2 rounded-md"
            onClick={() => {
              form.reset(defaultValues);
              setTitle("创建用户");
              setIsDialogOpen(!isDialogOpen);
            }}
          >
            <Plus className="mr-2 h-4 w-4" />
            创建
          </Button>
        </div>
        <Separator />

        <CustomDndTable
          totalCount={totalCount}
          defaultFilterColumn="username"
          columns={columns}
          data={userList}
          loading={loading}
          showImportButton={true}
          onSubmitFiles={handleUploadSubmit}
        />

        <Dialog
          open={isDialogOpen}
          onOpenChange={() => setIsDialogOpen(!isDialogOpen)}
        >
          <DialogContent className="max-w-3xl h-[80vh] overflow-y-auto">
            <DialogTitle></DialogTitle>
            <div className="">
              {/* 浏览器会寻找表单中的password输入框，自动填充之前的密码。
                Chrome等浏览器autoComplete=off不起作用。放在这里起到蜜罐
                的作用。但不能解决用户名自动填充和点击真实的密码框下拉列表的问题。
                蜜罐不能用display: "none"或visibility: "hidden"隐藏，否则失效
              */}
              <input
                type="password"
                style={{
                  width: "1px",
                  height: "1px",
                  position: "absolute",
                  border: "0px",
                  padding: "0px",
                }}
              />
              <Form {...form}>
                <form
                  onSubmit={form.handleSubmit(onFormSubmit)}
                  className="w-full space-y-8"
                >
                  {/* <div className="gap-8 md:grid md:grid-cols-3"> */}
                  <div className="flex flex-col gap-4">
                    <FormField
                      control={form.control}
                      name="id"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>ID</FormLabel>
                          <FormControl>
                            <Input
                              placeholder="id"
                              {...field}
                              disabled={true}
                              autoComplete="off"
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="username"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>用户名</FormLabel>
                          <FormControl>
                            <Select
                              options={employeeList}
                              // 本地有一层过滤，Lable中必须包含检索字段
                              getOptionLabel={(option: EmployeeI) =>
                                `${option.code} ${option.name} ${option.py} ${option.pinyin} ${option.department}`
                              }
                              getOptionValue={(option: EmployeeI) =>
                                option.code
                              }
                              onInputChange={handleSelectInputChange}
                              value={field.value}
                              onChange={(option: SingleValue<EmployeeI>) => {
                                field.onChange(option);
                                if (option) {
                                  form.setValue("fullName", option.name);
                                  form.setValue("empCode", option.code);
                                }
                              }}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="empCode"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex items-center justify-between">
                            <FormLabel>工号</FormLabel>
                          </div>
                          <FormControl>
                            <Input
                              disabled={true}
                              placeholder="工号"
                              {...field}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="fullName"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex items-center justify-between">
                            <FormLabel>姓名</FormLabel>
                          </div>
                          <FormControl>
                            <Input
                              disabled={true}
                              placeholder="姓名"
                              {...field}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="password"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex items-center justify-between">
                            <FormLabel>密码</FormLabel>
                          </div>
                          <FormControl>
                            <PasswordInput
                              placeholder="密码"
                              {...field}
                              // autoComplete="off"无效，只使用new-password能解决Chrome自动填充问题
                              // 但不解决点击密码框展示存的账号列表，蜜罐用于保险
                              autoComplete="new-password"
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="passwordAgain"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex items-center justify-between">
                            <FormLabel>密码确认</FormLabel>
                          </div>
                          <FormControl>
                            <PasswordInput placeholder="密码确认" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="isActive"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>在用标记</FormLabel>
                          <FormControl>
                            <Switch
                              className="ml-6"
                              checked={field.value}
                              onCheckedChange={field.onChange}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="roleIds"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>角色权限</FormLabel>
                          <Select
                            options={roleList.map((role: RoleI) => {
                              return {
                                value: role.id,
                                label: role.name,
                              };
                            })}
                            isMulti
                            isSearchable
                            value={field.value}
                            onChange={field.onChange}
                          />
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="depts"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>授权科室</FormLabel>
                          <Select
                            options={departmentList}
                            isMulti
                            isSearchable
                            value={field.value}
                            onChange={field.onChange}
                          />
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    {/* <FormField
                      control={form.control}
                      name="depts"
                      render={({ field }) => {
                        return (
                          <CustomTable
                            totalCount={departmentList.length}
                            defaultFilterColumn="name"
                            manualFiltering={false}
                            getRowId={(originalRow: any, index: number) => {
                              return originalRow.name;
                            }}
                            columns={deptColumns}
                            synchroniseUrl={false}
                            data={departmentList}
                            // initRowSelection={JSON.parse(field.name)}
                            onSelectionChange={(value: any) => {
                              console.log(value);
                              field.onChange(value);
                            }}
                          ></CustomTable>
                        );
                      }}
                    /> */}
                  </div>
                  <Button disabled={loading} className="ml-auto" type="submit">
                    提交
                  </Button>
                </form>
              </Form>
            </div>
          </DialogContent>
        </Dialog>

        <Dialog
          open={isResetDialogOpen}
          onOpenChange={() => setIsResetDialogOpen(!isResetDialogOpen)}
        >
          <DialogContent className="max-w-3xl h-[80vh] overflow-y-auto">
            <DialogTitle></DialogTitle>
            <div className="">
              {/* 浏览器会寻找表单中的password输入框，自动填充之前的密码。
                Chrome等浏览器autoComplete=off不起作用。放在这里起到蜜罐
                的作用。但不能解决用户名自动填充和点击真实的密码框下拉列表的问题。
                蜜罐不能用display: "none"或visibility: "hidden"隐藏，否则失效
              */}
              <input
                type="password"
                style={{
                  display: "none",
                  width: "1px",
                  height: "1px",
                  position: "absolute",
                  border: "0px",
                  padding: "0px",
                }}
              />
              <Form {...resetPasswordForm}>
                <form
                  onSubmit={resetPasswordForm.handleSubmit(
                    onResetPasswordFormSubmit
                  )}
                  className="w-full space-y-8"
                >
                  {/* <div className="gap-8 md:grid md:grid-cols-3"> */}
                  <div className="flex flex-col gap-4">
                    <FormField
                      control={resetPasswordForm.control}
                      name="id"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>ID</FormLabel>
                          <FormControl>
                            <Input
                              placeholder="id"
                              {...field}
                              disabled={true}
                              autoComplete="off"
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={resetPasswordForm.control}
                      name="password"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex items-center justify-between">
                            <FormLabel>密码</FormLabel>
                          </div>
                          <FormControl>
                            <PasswordInput
                              placeholder="密码"
                              {...field}
                              // autoComplete="off"无效，只使用new-password能解决Chrome自动填充问题
                              // 但不解决点击密码框展示存的账号列表，蜜罐用于保险
                              autoComplete="new-password"
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={resetPasswordForm.control}
                      name="passwordAgain"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex items-center justify-between">
                            <FormLabel>密码确认</FormLabel>
                          </div>
                          <FormControl>
                            <PasswordInput placeholder="密码确认" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                  <Button disabled={loading} className="ml-auto" type="submit">
                    提交
                  </Button>
                </form>
              </Form>
            </div>
          </DialogContent>
        </Dialog>
      </div>
    </PageContainer>
  );
};

export default page;
